package com.example.pcbcsmbackend.service;

import com.example.pcbcsmbackend.entity.Order;
import com.example.pcbcsmbackend.entity.OrderDetail;
import com.example.pcbcsmbackend.repository.OrderRepository;
import com.example.pcbcsmbackend.repository.OrderDetailRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

@Service
public class OrderService {
    
    @Autowired
    private OrderRepository orderRepository;
    
    @Autowired
    private OrderDetailRepository orderDetailRepository;
    
    @Autowired
    private ProductService productService;
    
    // 创建订单
    @Transactional
    public Order createOrder(Integer userId, BigDecimal totalAmount, String shippingAddress, 
                           String contactInfo, String paymentMethod, List<OrderDetail> orderDetails) {
        // 创建订单 - 默认状态为待确认订单
        Order order = new Order(userId, "pending", totalAmount, shippingAddress, contactInfo, paymentMethod);
        
        // 关键一步：在保存订单之前，设置双向关系
        for (OrderDetail detail : orderDetails) {
            detail.setOrder(order);
        }
        order.setOrderDetails(orderDetails);
        
        Order savedOrder = orderRepository.save(order);
        
        // 减少商品库存
        for (OrderDetail detail : savedOrder.getOrderDetails()) {
            productService.decreaseStock(detail.getProductId(), detail.getQuantity());
        }
        
        return savedOrder;
    }
    
    // 根据用户ID获取订单
    public List<Order> getOrdersByUserId(Integer userId) {
        return orderRepository.findByUserIdOrderByPurchaseTimeDesc(userId);
    }
    
    // 根据ID查找订单
    public Optional<Order> findById(Integer orderId) {
        return orderRepository.findById(orderId);
    }
    
    // 获取所有订单
    public List<Order> getAllOrders() {
        return orderRepository.findAllByOrderByPurchaseTimeDesc();
    }
    
    // 根据订单状态获取订单
    public List<Order> getOrdersByStatus(String status) {
        return orderRepository.findByOrderStatus(status);
    }
    
    // 更新订单状态
    public void updateOrderStatus(Integer orderId, String status) {
        Optional<Order> orderOpt = orderRepository.findById(orderId);
        if (orderOpt.isPresent()) {
            Order order = orderOpt.get();
            order.setOrderStatus(status);
            orderRepository.save(order);
        } else {
            throw new RuntimeException("订单不存在");
        }
    }
    
    // 更新订单信息（管理员功能）
    @Transactional
    public Order updateOrder(Integer orderId, String orderStatus, String paymentMethod, 
                           String shippingAddress, String contactInfo, BigDecimal totalAmount, 
                           List<OrderDetail> newOrderDetails) {
        Optional<Order> orderOpt = orderRepository.findById(orderId);
        if (!orderOpt.isPresent()) {
            throw new RuntimeException("订单不存在");
        }
        
        Order order = orderOpt.get();
        
        // 更新订单基本信息
        if (orderStatus != null) order.setOrderStatus(orderStatus);
        if (paymentMethod != null) order.setPaymentMethod(paymentMethod);
        if (shippingAddress != null) order.setShippingAddress(shippingAddress);
        if (contactInfo != null) order.setContactInfo(contactInfo);
        if (totalAmount != null) order.setTotalAmount(totalAmount);
        
        // 更新订单详情
        if (newOrderDetails != null && !newOrderDetails.isEmpty()) {
            // 删除现有的订单详情
            orderDetailRepository.deleteByOrder_OrderId(orderId);
            
            // 添加新的订单详情
            for (OrderDetail detail : newOrderDetails) {
                detail.setOrder(order);
                detail.setDetailId(null); // 确保是新记录
            }
            order.setOrderDetails(newOrderDetails);
        }
        
        return orderRepository.save(order);
    }
    
    // 获取订单详情
    public List<OrderDetail> getOrderDetails(Integer orderId) {
        return orderDetailRepository.findByOrder_OrderId(orderId);
    }
    
    // 批量更新订单状态
    @Transactional
    public void batchUpdateOrderStatus(List<Integer> orderIds, String status) {
        List<Order> ordersToUpdate = orderRepository.findAllById(orderIds);
        for (Order order : ordersToUpdate) {
            order.setOrderStatus(status);
        }
        orderRepository.saveAll(ordersToUpdate);
    }
    
    // 删除订单
    @Transactional
    public void deleteOrder(Integer orderId) {
        if (!orderRepository.existsById(orderId)) {
            throw new RuntimeException("订单不存在");
        }
        orderRepository.deleteById(orderId);
    }
    
    // 批量删除订单
    @Transactional
    public void batchDeleteOrders(List<Integer> orderIds) {
        orderRepository.deleteAllById(orderIds);
    }
} 